package com.example.book.api;

import com.alibaba.fastjson.JSONObject;
import com.example.book.base.ApiBaseController;
import com.example.book.base.Result;
import com.example.book.common.annotation.LoginIgnore;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.domain.wx.FullUserInfo;
import com.example.book.domain.wx.UserInfo;
import com.example.book.domain.wx.WxUser;
import com.example.book.wx.service.WxUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Pangx
 * 微信用户管理
 */
@RestController
@RequestMapping("/api/wxUser")
public class ApiWxUserController extends ApiBaseController {

    @Value("${wx.access_token}")
    private String access_token_url;

    @Value("${wx.login}")
    private String login_url;

    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RedisService redisService;

    @ModelAttribute
    public WxUser get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return wxUserService.get(id);
        } else {
            return new WxUser();
        }
    }

    /**
     * 小程序登录  post请求接收参数 不能够映射
     *
     * @return
     */
    @PostMapping("/login")
    @LoginIgnore
    public Result loginByWx(String userInfo, String code) {

        if (StringUtils.isBlank(userInfo)) {
            return Result.error("登陆失败");
        }

        UserInfo ui = JSONObject.parseObject(userInfo, UserInfo.class);
        JSONObject object = JSONObject.parseObject(restTemplate.getForObject(login_url + code + "&grant_type=authorization_code", String.class));
        String openid = (String) object.get("openid");
        String unionid = (String) object.get("unionid");

        if (StringUtils.isBlank(openid)){
            return Result.error("登录失败");
        }

        WxUser user = new WxUser();
        user.setOpenid(openid);
        WxUser wxUser = wxUserService.get(user);
        if (wxUser == null) {
            wxUser = new WxUser();
            wxUser.setOpenid(openid);
            wxUser.setAvatar(ui.getAvatarUrl());
            wxUser.setGender(ui.getGender());
            wxUser.setLoginName(ui.getNickName());
            if (StringUtils.isNotBlank(unionid)) {
                wxUser.setUnionid(unionid);
            }
            wxUser.setOpenid(openid);
            wxUserService.save(wxUser);
        } else {
            wxUser.setAvatar(ui.getAvatarUrl());
            wxUser.setLoginName(ui.getNickName());
            if (StringUtils.isNotBlank(unionid)) {
                wxUser.setUnionid(unionid);
            }
            wxUserService.save(wxUser);
        }

        ui.setOpenid(openid);
        ui.setUid(wxUser.getId());
        ui.setRegisterTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(wxUser.getCreateDate()));

        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = Constants.uuid();
            redisService.set(Constants.WX_API_TOKEN + token, ui, 60 * 60 * 24L * 7);
        } else {
            redisService.set(Constants.WX_API_TOKEN + token, ui, 60 * 60 * 24L * 7);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userInfo", ui);
        return Result.success("success", map);
    }

    /**
     * 检测用户登录状态
     *
     * @return
     */
    @GetMapping("/checkToken")
    @LoginIgnore
    public Result checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            return Result.error();
        }
        UserInfo userInfo = (UserInfo) redisService.get(Constants.WX_API_TOKEN + token);
        if (userInfo == null) {
            return Result.error();
        }
        return Result.success("success", userInfo);
    }

}
